package com.lanxin.qx.service.impl;

import com.lanxin.qx.entity.QxFunction;
import com.lanxin.qx.mapper.QxFunctionMapper;
import com.lanxin.qx.mapper.QxRoleMapper;
import com.lanxin.qx.service.IQxFunctionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2025-08-19
 */
@Service
public class QxFunctionServiceImpl extends ServiceImpl<QxFunctionMapper, QxFunction> implements IQxFunctionService {

    @Autowired
    private QxFunctionMapper qxFunctionMapper;

    @Override
    public List<QxFunction> listQxFunction(Integer oid) {
        return qxFunctionMapper.listMyFunction(oid);
    }

    @Override
    public QxFunction functions(Integer oid) {
        return qxFunctionMapper.functions(oid);
    }

    @Override
    public Map<QxFunction, List<QxFunction>> getFunctionsGroupByParent() {
        // 1.查询所有权限
        List<QxFunction> allFunctions = this.list();
        if (allFunctions == null) {
            return new HashMap<>();
        }

        // 2.分离父权限（parentid为null或0）和子权限
        List<QxFunction> parentFunctions = new ArrayList<>();
        Map<Integer, List<QxFunction>> childMap = new HashMap<>();

        for (QxFunction func : allFunctions) {
            Integer parentId = func.getParentid();
            if (parentId == null || parentId == 0) {
                parentFunctions.add(func);
            } else {
                childMap.computeIfAbsent(parentId, k -> new ArrayList<>()).add(func);
            }
        }

        // 3.组装父-子权限映射
        Map<QxFunction, List<QxFunction>> result = new HashMap<>();
        for (QxFunction parent : parentFunctions) {
            result.put(parent, childMap.getOrDefault(parent.getOid(), new ArrayList<>()));
        }
        return result;
    }

    @Override
    public List<Integer> getFunctionIdsByRoleId(Integer roleId) {
        return qxFunctionMapper.selectFunctionIdsByRoleId(roleId);
    }
}